package com.sanyang.lawyer.controller.record;

import com.sanyang.lawyer.entity.*;
import com.sanyang.lawyer.service.Case.Case_courtService;
import com.sanyang.lawyer.service.client.ClientService;
import com.sanyang.lawyer.service.hr.HrEmpService;
import com.sanyang.lawyer.service.record.RecordService;
import com.sanyang.lawyer.utils.FastDFSutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("record")
public class RecordController {

    @Autowired
    private RecordService recordService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private Case_courtService case_courtService;
    @Autowired
    private HrEmpService hrEmpService;
    @Autowired
    private FastDFSutils fastDFSutils;
//    查询所有的归档记录
    @RequestMapping("listmyrecordall")
    public Map<String,Object> listmyrecordall(Record record,HttpServletRequest request){
        String empid = request.getParameter("empid");
        String stateclient = request.getParameter("stateclient");
        String casetext = request.getParameter("casetext");
        System.out.println("casetext:"+casetext+" empid:"+empid);
        Recordpage recordpage = new Recordpage(record,request);
        Map<String,Object> maps=new HashMap<String, Object>();
        maps.put("pagetext",recordpage);
        maps.put("lawyer",empid);
        if(casetext!=""&&casetext!=null){
            switch (stateclient){
                case "1":
                    String casetext1=null;
                    casetext1=casetext;
                    maps.put("casetext1",casetext1);  //案号
                    break;
                case "2":
                    String casetext2=null;
                    casetext2=casetext;
                    maps.put("casetext2", casetext2);  //归档文件名称
                    break;
            }
        }
        System.out.println("map:"+maps.get("casetext1"));
        List<Record> records=recordService.listmyrecordall(maps);
        Map<String,Object> map = new HashMap<String,Object>();
        Integer count = recordService.getcountrecord(recordpage);
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",records);
        return map;
    }
    @RequestMapping("listrecordall")
    public Map<String,Object> listrecordall(Record record,HttpServletRequest request){
        String stateclient = request.getParameter("stateclient");
        String casetext = request.getParameter("casetext");
        Recordpage recordpage = new Recordpage(record,request);
        Map<String,Object> maps=new HashMap<String, Object>();
        maps.put("pagetext",recordpage);
        if(casetext!=""&&casetext!=null){
            switch (stateclient){
                case "1":
                    String casetext1=null;
                    casetext1=casetext;
                    maps.put("casetext1",casetext1);  //案号
                    break;
                case "2":
                    String casetext2=null;
                    casetext2=casetext;
                    List<Hr_emp> emp = hrEmpService.getByEmpName(casetext2);
                        maps.put("casetext2", emp.get(0).getEmpId());  //委托人
                    break;
                case "3":
                    String casetext3=null;
                    casetext3=casetext;
                    maps.put("casetext3", casetext3);  //归档文件名称
                    break;
            }
        }
        List<Record> records=recordService.listrecordall(maps);
        Map<String,Object> map = new HashMap<String,Object>();
        Integer count = recordService.getcountrecord(recordpage);
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        map.put("data",records);
        return map;
    }
//    查询单个的归档记录
    @RequestMapping("getbyrecord")
    public Record getbyrecord(int recordId){
        Record record = recordService.getbyrecord(1);
        return record;
    }

    //查询案件
    @RequestMapping("listallcase")
    public Map<String,Object> listallcase(Case_law caselaw, HttpServletRequest request){
        String stateclient = request.getParameter("stateclient");
        String casetext = request.getParameter("casetext");
        Recordpage recordpage = new Recordpage(caselaw,request);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("pagetext",recordpage);
        if(casetext!=""&&casetext!=null){
            switch (stateclient){
                case "1":
                    String casetext1=null;
                    casetext1=casetext;
                    map.put("casetext1",casetext1);  //案号
                    break;
                case "2":
                    String casetext2=null;
                    casetext2=casetext;
                    Client law1 = clientService.getbyname(casetext2);
                    if(law1.getClientName()!=null||law1.getClientName()!="") {
                        map.put("casetext2", law1.getClientId());  //委托人
                    }
                    break;
                case "3":
                    String casetext3=null;
                    casetext3=casetext;
                    Client law2 = clientService.getbyname(casetext3);
                    if(law2.getClientName()!=null&&law2.getClientName()!=""){
                      map.put("casetext3",law2.getClientId());  //对方当事人
                    }
                    break;
                case "4":
                    String casetext4=null;
                    casetext4=casetext;
                    map.put("casetext4",casetext4);  //案由
                    break;
                case "5":
                    String casetext5=null;
                    casetext5=casetext;
                    List<Hr_emp> emp = hrEmpService.getByEmpName(casetext5);
                    if(emp.size()>=1) {
                        map.put("casetext5",emp.get(0).getEmpId());  //承办律师
                    }
                    break;
                case "6":
                    String casetext6=null;
                    casetext6=casetext;
                    Case_court case_court=case_courtService.querybyname(casetext6);
                    if(case_court.getCourtName()!=null&&case_court.getCourtName()!=""){
                      map.put("casetext6",case_court.getCourtId());  //受理法院
                    }
                    break;
            }
        }
        List<Case_law> caselaws=recordService.listallid(map);
        Integer count = recordService.listcountcase(map);
        Map<String,Object> maps = new HashMap<String,Object>();
        if(caselaws.size()<=0){
            count=0;
            maps.put("code",0);
            maps.put("msg","");
            maps.put("count",count);
            maps.put("data","");
        }else{
            maps.put("code",0);
            maps.put("msg","");
            maps.put("count",count);
            maps.put("data",caselaws);
        }
        return maps;
    }
    @RequestMapping("transmitted")
    public String transmitted(@RequestParam("file") MultipartFile file, int empid, String caseName) {
        String fileName = file.getOriginalFilename();//获取文件名
        Record record = new Record();
        String url = "";//存储url字段
        try {
            if (empid!=0&&caseName!=null&&caseName!=""){//判断基本信息完善否!
                if (!fileName.equals("") && fileName != null) {//判断是否有需要上传的文件
                    System.out.println("filename : "+fileName);
                    Hr_emp emp = hrEmpService.getById(empid);//通过当前用户编号查询出用户信息
                    record.setEmpId(emp);
                    record.setArchivefile(fileName);
                    Case_law case_law = recordService.getbycaselaw(caseName);
                    record.setCaseId(case_law);
                    Date currentTime = new Date();//获取当前时间
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");//规定日期格式
                    record.setTurnovertime(formatter.format(currentTime));
                    url = fastDFSutils.uploadfile(file);//调用上传方法  返回url地址
                    record.setUrl(url);//文件地址
                    recordService.insertrecord(record);//执行插入sql
                    return "ok";//成功执行 返回ok
                }else {
                    return "no";
                }
            } else {
                if (url!=null&&url!=""){
                    fastDFSutils.deletefile(url);//SQL未执行,则删除已上传文件
                }
                return "no";//返回失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (url!=null&&url!=""){
                fastDFSutils.deletefile(url);//报错,则删除已上传文件

            }
            return "no!";//报错
        }
    }
    //修改档案文件
    @RequestMapping("updatetransmitted")
    public String updatetransmitted(@RequestParam("file") MultipartFile file, int empid, String caseName,String recordId) {
        String fileName = file.getOriginalFilename();//获取文件名
        Record record = new Record();
        String url = "";//存储url字段
        try {
            if (empid!=0&&caseName!=null&&caseName!=""){//判断基本信息完善否!
                if (!fileName.equals("")&& fileName != null) {//判断是否有需要上传的文件
                    System.out.println("filename : "+fileName);
                    Hr_emp emp = hrEmpService.getById(empid);//通过当前用户编号查询出用户信息
                    record.setEmpId(emp);
                    record.setArchivefile(fileName);
                    Case_law case_law = recordService.getbycaselaw(caseName);
                    record.setCaseId(case_law);
                    Date currentTime = new Date();//获取当前时间
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");//规定日期格式
                    record.setTurnovertime(formatter.format(currentTime));
                    deleteos(recordId);
                    url = fastDFSutils.uploadfile(file);//调用上传方法  返回url地址
                    record.setUrl(url);//文件地址
                    recordService.insertrecord(record);//执行插入sql
                    return "ok";//成功执行 返回ok
                }else {
                    return "no";
                }
            } else {
                if (url!=null&&url!=""){
                    fastDFSutils.deletefile(url);//SQL未执行,则删除已上传文件
                }
                return "no";//返回失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (url!=null&&url!=""){
                fastDFSutils.deletefile(url);//报错,则删除已上传文件
            }
            return "no!";//报错
        }
    }

    @RequestMapping("queryurl")
    public String queryurl(String recordId){
        System.out.println("recordId："+recordId);
        Record record = recordService.getbyrecord(Integer.parseInt(recordId));
        System.out.println("record1: "+record.toString());
        String urltxt=record.getUrl();
        System.out.println("url:"+urltxt);
        int beginurl=urltxt.lastIndexOf("/")-6;
        System.out.println("url:"+urltxt.substring(beginurl));
        return urltxt.substring(beginurl);
    }
    //下载副件
    @RequestMapping("downloados")
    public void downfile(HttpServletResponse response,@RequestParam String fileurl)throws Exception{
        if(fileurl!=null){
        // 获取文件
        Record record = recordService.getbyurl(fileurl);
        byte[] bytes = fastDFSutils.downloadfile(record.getUrl());
        //设置相应类型application/octet-stream        （注：applicatoin/octet-stream 为通用，一些其它的类型苹果浏览器下载内容可能为空）
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(record.getArchivefile(),"UTF-8"));
        // 写入到流
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
        }
    }
    //删除消息
    @RequestMapping("deleteos")
    public String deleteos(String recordId){
        String url = queryurl(recordId);
        String headurl = "http://39.96.48.147:8888/group1/M00";
        String intacturl=headurl+url;
        System.out.println("完整url:"+intacturl);
        Record record = recordService.getbyrecord(Integer.parseInt(recordId));
        if (url!=null&&!url.equals("")){
            System.out.println("进入删除判定！");
            fastDFSutils.deletefile(intacturl);
            recordService.deleterecord(record);
        }//文件存在,就干掉它
        return "ok";
    }
}
